﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace Common
{
    public class HttpHelper
    {
        /// <summary>
        /// http访问Get方法
        /// </summary>
        /// <typeparam name="T">访问返回的类</typeparam>
        /// <param name="strURL">访问地址</param>
        /// <returns></returns>
        public static T GetHttpRequest<T>(string strURL)
        {

            // 创建一个HTTP请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //request.Method="get";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

            string responseText = myreader.ReadToEnd();
            myreader.Close();

            //转为实体类
            return new JsonHelper().JSONToObject<T>(responseText);
        }

        /// <summary>
        /// http访问Post方法
        /// </summary>
        /// <typeparam name="T">访问返回的类</typeparam>
        /// <param name="strURL">访问地址</param>
        /// <param name="parameters">访问参数</param>
        /// <returns></returns>
        public static T PostHttpRequest<T>(string strURL, List<UrlParameters> parameters)
        {
            string result = string.Empty;
            try
            {
                //创建http请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
                request.ServicePoint.Expect100Continue = false;

                //Post请求方式
                request.Method = "POST";
                request.KeepAlive = true;
                request.Credentials = CredentialCache.DefaultCredentials;

                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";

                StringBuilder builder = new StringBuilder();
                foreach (var item in parameters)
                {
                    builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.key, item.value);
                }
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(builder.ToString().TrimEnd('&'));
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请 求流
                System.IO.Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                // 关闭请求流
                writer.Close();
                HttpWebResponse response;
                // 获得响应流
                response = (HttpWebResponse)request.GetResponse();
                StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = myreader.ReadToEnd();
                myreader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //转为实体类
            return new JsonHelper().JSONToObject<T>(result);
        }

        public static T PostHttpRequest<T>(string url, List<string> files, string contentType, List<UrlParameters> parameters)
        {
            string result = string.Empty;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (UrlParameters parame in parameters)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, parame.key, parame.value);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            //rs.Write(boundarybytes, 0, boundarybytes.Length);


            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            foreach (var item in files)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string header = string.Format(headerTemplate, "images", item, contentType);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                FileStream fileStream = new FileStream(item, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    rs.Write(buffer, 0, bytesRead);
                }
                fileStream.Close();
            }

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);

                result = reader2.ReadToEnd();
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }

            return new JsonHelper().JSONToObject<T>(result);
        }
    }
}
